var spider = require('./node.spider');
var cheerio = require('cheerio');
var url_node = require('url');
var Iconv = require('iconv-lite');
var pinyin = require('node-pinyin');
var insertDB = require('./insert.db');
var utils = require('../../dao/utils');


function sort(title) {
    title = title.replace(/(^s*)|(s*$)/g, "");
    let str = title.substring(0, 1).toUpperCase();

    // 英文字符，数字
    if (str >= 'A' && str <= 'Z') {
        return str;
    } else if (str >= 0 && str <= 9) {
        return '0-9';
    } else {

        var p = pinyin(str, { "style": "normal" })[0][0].toUpperCase();
        // console.log(p);
        p = p.substring(0, 1).toUpperCase();


        // console.log((p >= 'A') && (p <= 'Z'));

        if ((p >= 'A') && (p <= 'Z')) {
            return p;
        } else {
            return '其他';
        }


    }


}

// setting
var setting = {
    start: {
        url: 'http://comic.kukudm.com/comictype/3_*PageReplace*.htm',
        pageItem: 1,
        curPage: 1,
        totalPage: 107,
        timeout: 90000
    },
    parseHandel: function (body, url, _default) {
        var res;
        try {
            // console.log(body);
            res = Iconv.decode(body, 'gbk');
            // console.log(res);
        } catch (e) {
            spider.spider(url, _default);
            return;
        }


        var $ = cheerio.load(res);

        kukuHtml($, url, _default);

        // console.log(data);

        /*if (_default.start.curPage == 1) {
            // /comictype/3_107.htm
            var href = $('.pages a').eq(-1).attr('href').replace('.htm', '');
            var n = href.split('/');
            _default.start.totalPage = n[n.length - 1];
        }*/

        _default.pageNext(_default);



    },
    parseDetailHandel: function (body, url, _default) {
        var res;
        try {
            res = Iconv.decode(body, 'gbk');
        } catch (e) {

            spider.spiderDetail(url, _default);
            return;
        }


        var $ = cheerio.load(res);

        var data = kukuDetailHtml($, url, _default);

        if (data == false) {
            return;
        }

        insertDB(data, _default);
        // console.log(data);
    }


};

spider.init(setting);



// kuku网站爬取
function kukuHtml($, url, _default) {

    var urlObj = url_node.parse(url);
    var protocol = urlObj.protocol;
    var hostname = urlObj.hostname;

    var host = protocol + "//" + hostname;

    var liArry = $('#comicmain dd');

    if (liArry.length == 0) {
        console.log('no lis');
        return false;
    }

    for (var i = 0; i < liArry.length; i++) {
        var item = liArry.eq(i);

        if (item.hasClass('ad_360_item')) {
            continue;
        }

        var url = host + item.find('a').eq(1).attr('href');
        var title = item.find('a').eq(1).text().replace(/(^s*)|(s*$)/g, "");
        //detail  

        spider.spiderDetail(url, _default, 5000, title);


    }

}

function kukuDetailHtml($, url, _default) {
    var urlObj = url_node.parse(url);
    var protocol = urlObj.protocol;
    var hostname = urlObj.hostname;

    var host = protocol + "//" + hostname;

    var contentTable = $('body').children('table').eq(4).children('tbody').children('tr').children('td').eq(1).find('table').eq(1).children('tbody').children('tr');

    var item = contentTable.eq(4).find('td').text().replace(/(^s*)|(s*$)/g, "");

    var title = contentTable.eq(0).find('td').text().replace(/(^s*)|(s*$)/g, "");

    var img = contentTable.eq(1).find('img').attr('src');

    title = title.slice(0, -2);



    if (item.length == 0) {
        return false;
    }

    var arry = item.split('|');

    // console.log(arry);

    var _auth = arry[0].split('：')[1];
    var time = arry[2].split('：')[1];

    // console.log(arry[1].split('：')[1]);

    var isFinish = arry[1].split('：')[1].replace(/(^s*)|(s*$)/g, "") == '连载' ? false : true;

    var chapter = [];


    var chaptersLis = $('#comiclistn dd');

    for (var i = 0; i < chaptersLis.length; i++) {
        var _cur = chaptersLis.eq(i);

        chapter.push({
            href: host + _cur.find('a').eq(0).attr('href').replace(/(^s*)|(s*$)/g, ""),
            chapter: _cur.find('a').eq(0).text().replace(/(^s*)|(s*$)/g, "")
        });
    }


    // var _sChapter = chapter.join(',');

    var data = {
        title: title,
        href: url,
        img: img,
        auth: _auth ? _auth.replace(/(^s*)|(s*$)/g, "") : null,
        auth_href: null,
        news: chapter.length>0? chapter[0]['chapter']:null,
        news_href: chapter.length>0?chapter[0]['href']:null,
        isFinish: isFinish,
        updateTime: time ? time.replace(/(^s*)|(s*$)/g, "") : null,
        type: null,
        letter: sort(title),
        info: utils.trim($('#ComicInfo').text()),
        domain: hostname,
        isUpdate: true,
        "chapters": chapter,
    };

    data.updateTime = new Date(data.updateTime);

    return data;
    // console.log(chapter);

}

